<template>
    <div class="personnel-maintenance-container">
        <div class="personal-maintenance-container-tree">
            <el-input v-model="filterText" style="width: 240px" placeholder="请输入内容" />
            <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data" :props="defaultProps"
                :default-expand-all="false" :filter-node-method="filterNode" @node-click="nodeClickHandle" />
        </div>
        <vxe-grid ref='xGrid' v-bind="gridOptions" v-on="gridEvent" style="width: 100%">
            <template #gender_default="{ row }">
                <span>{{ formatSex(row) }}</span>
            </template>
            <template #operate_default="{ row }">
                <vxe-button mode="text" icon="vxe-icon-edit" @click="editEvent(row)"></vxe-button>
                <vxe-button mode="text" icon="vxe-icon-delete" @click="removeEvent(row)"></vxe-button>
            </template>
        </vxe-grid>
    </div>
    <el-dialog v-model="dialogFormVisible" width="700px" :destroy-on-close="true">
        <template #header>
            <h1>新增</h1>
        </template>
        <el-form :model="form" size="large" :rules="rules" ref="dialogForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="用户编号" prop="userId" :label-width="formLabelWidth">
                        <el-input v-model="form.userId" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
                        <el-input v-model="form.userName" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
                        <el-input v-model="form.password" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="部门" prop="departement" :label-width="formLabelWidth">
                        <el-tree-select v-model="form.departement" :data="data" :check-strictly="false"
                            :render-after-expand="false" :props="{ value: 'id', label: 'label' }" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-select v-model="form.gender">
                            <el-option label="男" value="1" />
                            <el-option label="女" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="电话号码" :label-width="formLabelWidth">
                        <el-input v-model="form.phoneNumber" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱" :label-width="formLabelWidth">
                        <el-input v-model="form.email" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="入职日期" :label-width="formLabelWidth">
                        <el-date-picker v-model="form.joinedDate" type="date" style="width: 100%" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="danger" @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmHandle(dialogForm)">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { VxeUI } from 'vxe-table'
import { ElMessage, ElTree, ElMessageBox } from 'element-plus'
import { GetAllUser, UserRegister, UpdateUserMessage, DeleteUserMessage } from '@/request/api'

const dialogFormVisible = ref(false)
const dialogForm = ref();
const formLabelWidth = '80px'
const form = reactive({
    id: '',
    userId: '',
    userName: '',
    departement: '',
    gender: '',
    phoneNumber: '',
    email: '',
    joinedDate: '',
    password: '',
})
const rules = reactive({
    userId: [
        { required: true, message: '请输入用户编号', trigger: 'blur' },
    ],
    userName: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    departement: [
        { required: true, message: '请选择部门', trigger: 'change' },
    ],
})
interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
    children: 'children',
    label: 'label',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})
watch(dialogFormVisible, (val) => {
    if (!val) {
        Object.assign(form, {
            id: '',
            userId: '',
            userName: '',
            departement: '',
            gender: '',
            phoneNumber: '',
            email: '',
            joinedDate: '',
            password: '',
        })
    }
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
}

const data: Tree[] = [
    {
        id: 0,
        label: '项目部',
        children: [
            {
                id: 3,
                label: '开发部',
                children: [
                    {
                        id: 8,
                        label: '开发一组',
                    },
                    {
                        id: 9,
                        label: '开发二组',
                    },
                ],
            },
        ],
    },
    {
        id: 1,
        label: '产品部',
        children: [
            {
                id: 4,
                label: '研发部',
            },
            {
                id: 5,
                label: '设计部',
            },
        ],
    },
    {
        id: 2,
        label: '营销部',
        children: [
            {
                id: 6,
                label: '市场部',
            },
            {
                id: 7,
                label: '售前部',
            },
        ],
    },
];
function nodeClickHandle(data: Tree, a, b, c) {
    xGrid.value.commitProxy("query",{a:"kkkkkkk"});
    // console.log(data, a, b, c, "树点击事件",xGrid.value)
}
// 新增
async function confirmHandle(formEl) {
    console.log(formEl, "formEl")
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (!form.id) {
                try {
                    let res = await UserRegister(JSON.stringify(form));
                    ElMessage.success(res.data.message);
                    dialogFormVisible.value = false;
                    xGrid.value.commitProxy("query");
                } catch (error) {
                    ElMessage.error(error.message)
                }
            } else {
                try {
                    let res = await UpdateUserMessage(JSON.stringify(form));
                    ElMessage.success(res.data.message);
                    dialogFormVisible.value = false;
                    xGrid.value.commitProxy("query");
                } catch (error) {
                    ElMessage.error(error.message)
                }
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}
// 编辑
async function editEvent(row) {
    dialogFormVisible.value = true;
    row.id = row._id;
    Object.assign(form, row);
}
async function removeEvent(row) {
    ElMessageBox.confirm(
        '确定要要删除当前数据?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            let res = await DeleteUserMessage({ id: row._id });
            ElMessage.success(res.data.message);
            xGrid.value.commitProxy("query");
        } catch (error) {
            ElMessage.error(error.message)
        }
    }).catch(() => {
        console.log("取消删除")
    })
}
const serveApiUrl = 'https://api.vxetable.cn/demo'
const xGrid = ref()
const gridOptions = reactive({
    border: true,
    // showHeaderOverflow: true,
    // showOverflow: true,
    keepSource: true,
    id: 'full_edit_1',
    height: "auto",
    rowConfig: {
        keyField: 'id',
        isHover: true
    },
    columnConfig: {
        resizable: true
    },
    customConfig: {
        storage: true,
        checkMethod({ column }) {
            if (['nickname', 'role'].includes(column.field)) {
                return false
            }
            return true
        }
    },
    printConfig: {
        columns: [
            { field: 'name' },
            { field: 'email' },
            { field: 'nickname' },
            { field: 'age' },
            { field: 'amount' }
        ]
    },
    sortConfig: {
        trigger: 'cell',
        remote: true
    },
    filterConfig: {
        remote: true
    },
    pagerConfig: {
        enabled: true,
        // currentPage: 1,
        pageSize: 10,
        pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
    },
    validConfig: {
        msgMode: 'full' // 设置为支持显示多个校验消息
    },
    formConfig: {
        titleWidth: 80,
        titleAlign: 'right',
        items: [
            { field: 'userId', title: '用户编号', span: 8, itemRender: { name: 'VxeInput', props: { placeholder: '请输入用户编号' } } },
            { field: 'userName', title: '用户名称', span: 8, itemRender: { name: 'VxeInput', props: { placeholder: '请输入用户名称' } } },
            {
                span: 8,
                collapseNode: false,
                itemRender: {
                    name: 'VxeButtonGroup',
                    options: [
                        { type: 'submit', content: '搜索', status: 'primary' },
                        { type: 'reset', content: '重置' }
                    ]
                }
            },
            //{ field: 'departement', title: '部门', visible: true, span: 8, itemRender: { name: 'VxeInput', props: { placeholder: '请输入部门' } } },
        ]
    },
    toolbarConfig: {
        size: 'medium',
        buttons: [
            { code: 'added', name: '新增', status: 'primary' },
        ],
        refresh: true,
        import: true,
        export: true,
        print: true,
        zoom: true,
        custom: true // 显示自定义列按钮
    },
    proxyConfig: {
        seq: true,
        sort: true,
        filter: true,
        form: true,
        props: {
            // 对应响应结果 Promise<{ result: [], page: { total: 100 } }>
            result: 'result',
            total: 'page.total' // 配置响应结果总页数字段
        },
        // 只接收Promise，具体实现自由发挥
        ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: async ({ page, sorts, filters, form,a }) => {
                const queryParams = Object.assign({}, form)
                console.log(page, sorts, filters,form,a)
                // 处理分页条件
                queryParams.currentPage = page.currentPage
                queryParams.pageSize = page.pageSize
                // 处理排序条件
                const firstSort = sorts[0]
                if (firstSort) {
                    queryParams.sort = firstSort.field
                    queryParams.sortBy = firstSort.order
                }
                // 处理筛选条件
                filters.forEach(({ field, values }) => {
                    queryParams[field] = values.join(',')
                })
                console.log(queryParams)
                let res = await GetAllUser(queryParams)
                return res.data
            },
            // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
            delete: ({ body }) => {
                return fetch(`${serveApiUrl}/api/pub/save`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(response => response.json())
            },
            // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
            save: ({ body }) => {
                return fetch(`${serveApiUrl}/api/pub/save`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(response => response.json())
            }
        }
    },
    columns: [
        { type: 'checkbox', align: 'center', minWidth: "auto" },
        { type: 'seq', title: "序号", align: 'center', showOverflow: "title" },
        { field: 'userId', title: '用户编号', align: 'center', showOverflow: "title" },
        { field: 'userName', title: '用户名称', align: 'center', sortable: false, showOverflow: "title" },
        { field: 'gender', title: '性别', align: 'center', showOverflow: "title", slots: { default: "gender_default" }, filters: [{ label: '男', value: '1' }, { label: '女', value: '0' }] },
        { field: 'departement', title: '部门', align: 'center', showOverflow: "title", minWidth: 80 },
        { field: 'email', title: '邮箱', align: 'center', showOverflow: "title", minWidth: 80 },
        { field: 'phoneNumber', title: '电话号码', visible: true, align: 'center', showOverflow: "title", minWidth: 80 },
        { field: 'joinedDate', title: '入职日期', sortable: true, align: 'center', showOverflow: "title" },
        { title: '操作', align: 'center', fixed: "right", width: "200", slots: { default: "operate_default" } },
    ],
    importConfig: {
        remote: true,
        types: ['xlsx'],
        modes: ['insert'],
        // 自定义服务端导入
        importMethod({ file }) {
            const $grid = xGrid.value
            const formBody = new FormData()
            formBody.append('file', file)
            return fetch(`${serveApiUrl}/api/pub/import`, { method: 'POST', body: formBody }).then(response => response.json()).then(data => {
                VxeUI.modal.message({ content: `成功导入 ${data.result.insertRows} 条记录！`, status: 'success' })
                // 导入完成，刷新表格
                if ($grid) {
                    $grid.commitProxy('query')
                }
            }).catch(() => {
                VxeUI.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
            })
        }
    },
    exportConfig: {
        remote: true,
        types: ['xlsx'],
        modes: ['current', 'selected', 'all'],
        // 自定义服务端导出
        exportMethod({ options }) {
            const $grid = xGrid.value
            if ($grid) {
                const proxyInfo = $grid.getProxyInfo()
                // 传给服务端的参数
                const body = {
                    filename: options.filename,
                    sheetName: options.sheetName,
                    isHeader: options.isHeader,
                    original: options.original,
                    mode: options.mode,
                    pager: proxyInfo ? proxyInfo.pager : null,
                    ids: options.mode === 'selected' ? options.data.map((item) => item.id) : [],
                    fields: options.columns.map((column) => {
                        return {
                            field: column.field,
                            title: column.title
                        }
                    })
                }
                // 开始服务端导出
                return fetch(`${serveApiUrl}/api/pub/export`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(response => response.json()).then(data => {
                    if (data.id) {
                        VxeUI.modal.message({ content: '导出成功，开始下载', status: 'success' })
                        // 读取路径，请求文件
                        fetch(`${serveApiUrl}/api/pub/export/download/${data.id}`).then(response => {
                            response.blob().then(blob => {
                                // 开始下载
                                VxeUI.saveFile({ filename: '导出数据', type: 'xlsx', content: blob })
                            })
                        })
                    }
                }).catch(() => {
                    VxeUI.modal.message({ content: '导出失败！', status: 'error' })
                })
            }
            return Promise.resolve()
        }
    },
    editRules: {
        name: [
            { required: true, message: '名称必填' },
            { min: 3, max: 50, message: '名称长度在 3 到 50 个字符' }
        ],
        email: [
            { required: true, message: '邮件必须填写' }
        ],
        role: [
            { required: true, message: '角色必须填写' }
        ]
    },
    editConfig: {
        trigger: 'click',
        mode: 'row',
        showStatus: true
    }
})
const gridEvent = {
    proxyQuery() {
        console.log('数据代理查询事件')
    },
    proxyDelete() {
        console.log('数据代理删除事件')
    },
    proxySave() {
        console.log('数据代理保存事件')
    },
    toolbarButtonClick({ code }: { code: string }, button, event) {
        switch (code) {
            case "added":
                dialogFormVisible.value = true;
                console.log("添加")
                break;
            case "batchDelete":
                console.log("批量删除")
                break;
        }
    },
}
const formatSex = (row) => {
    return row.gender === '1' ? '男' : '女'
}
onMounted(() => {
    // const sexList = [
    //     { label: '女', value: '0' },
    //     { label: '男', value: '1' },
    // ]
    // const { formConfig, columns } = gridOptions
    // if (columns) {
    //     const sexColumn = columns[5]
    //     if (sexColumn && sexColumn.editRender) {
    //         sexColumn.editRender.options = sexList
    //     }
    // }
    // if (formConfig && formConfig.items) {
    //     const sexItem = formConfig.items[4]
    //     if (sexItem && sexItem.itemRender) {
    //         sexItem.itemRender.options = sexList
    //     }
    // }
})
</script>
<style lang="less" scoped>
.personnel-maintenance-container {
    display: flex;
    height: calc(100vh - 60px);
    width: 100%;

    .personal-maintenance-container-tree {
        display: flex;
        flex-direction: column;
        border: 1px solid rgba(67, 67, 67, 0.1);
        padding: 2px;
        margin: 0 2px 0 0;
    }
}
</style>